package com.exp.base.freemaker;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.ServletContext;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.filefilter.AbstractFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;

//TODO 待配置化
//@Component
public class ResourceVersionManager implements ServletContextAware,ApplicationListener{

	ServletContext servletContext;
	
	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	HashMap<String, String> md5map = new HashMap<String, String>();
	
	public String getMd5(String path){
		return md5map.get(path);
	}
	
	@Override
	public void onApplicationEvent(ApplicationEvent event) {
		if (event instanceof ContextRefreshedEvent) {
			md5map.clear();
			System.out.println("######################### 正在收集静态文件");
			String webappPath = servletContext.getRealPath("/");
			webappPath = FilenameUtils.separatorsToUnix(webappPath);
			webappPath = FilenameUtils.getFullPathNoEndSeparator(webappPath);
			
			System.out.println(webappPath);
			Iterator<File> fite = FileUtils.iterateFiles(new File(webappPath), new AbstractFileFilter() {
				@Override
				public boolean accept(File dir, String name) {
					if(StringUtils.endsWithIgnoreCase(name, "js")||StringUtils.endsWithIgnoreCase(name, "css")){
						return true;
					}else{
						return false;
					}
				}
			}, TrueFileFilter.TRUE);
			
			while(fite.hasNext()){
				File file = fite.next();
				try {
					String abpath = file.getAbsolutePath();
					abpath = FilenameUtils.separatorsToUnix(abpath);
					abpath = abpath.replace(webappPath,"" );
					System.out.println(abpath);
					md5map.put(abpath, DigestUtils.md5Hex(FileUtils.readFileToByteArray(file)));
				} catch (IOException e) {
				}
			}
			
			
			System.out.println("######################### 完成收集静态文件");
		}
	}

	
}
